package cn.aws360.boot.extend.sms.sdk;

import cn.aws360.boot.base.api.constant.BaseConstant;
import cn.aws360.boot.base.api.exception.ServiceException;
import cn.aws360.boot.extend.sms.api.SmsSenderApi;
import cn.aws360.boot.extend.sms.api.exception.SmsExceptionEnum;
import cn.aws360.boot.extend.sms.api.pojo.properties.AlibabaSmsProperties;
import com.alibaba.fastjson.JSON;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author junnan
 */
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(name = BaseConstant.APP + ".extend.sms.alibaba.enable", havingValue = "true")
public class AlibabaSmsServiceSdk implements SmsSenderApi {

    private final static String REGION = "cn-hangzhou";
    private final static String ENDPOINT_OVERRIDE = "dysmsapi.aliyuncs.com";
    private final AlibabaSmsProperties smsProperties;

    @Override
    public Boolean sendSms(String sign, String tplId, String mobile, Map<String, Object> paramMap) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(smsProperties.getAccessKeyId())
                .accessKeySecret(smsProperties.getAccessKeySecret()).build());

        AsyncClient smsClient = AsyncClient.builder().region(REGION).credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride(ENDPOINT_OVERRIDE))
                .build();

        SendSmsRequest request = SendSmsRequest.builder()
                .signName(sign)
                .templateCode(tplId)
                .phoneNumbers(mobile)
                .templateParam(JSON.toJSONString(paramMap))
                .build();

        try {
            SendSmsResponse response = smsClient.sendSms(request).get();
            log.info("【短信发送结果-阿里】response: {}", new Gson().toJson(response));
            return "ok".equalsIgnoreCase(response.getBody().getCode());
        } catch (Exception e) {
            throw new ServiceException(SmsExceptionEnum.SMS_SEND_ERROR_FOR_ALIBABA);
        } finally {
            smsClient.close();
        }
    }

}
